package com.unionfetch.content_home.ui.account

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.unionfetch.content_home.R
import com.unionfetch.content_home.adapter.AccountInfoListAdapter
import com.unionfetch.content_home.bean.DemoAccountInfo
import com.unionfetch.content_home.bean.DemoTradeAccount
import com.unionfetch.content_home.bean.TradeAccountModel
import com.unionfetch.content_home.bean.change2TradeAccountModel
import com.unionfetch.content_home.bean.request.ModifyDemoLeverRequest
import com.unionfetch.content_home.bean.request.ModifyLeverRequest
import com.unionfetch.content_home.contract.AccountContract
import com.unionfetch.content_home.presenter.AccountPresenter
import com.unionfetch.content_home.ui.dialog.ModifyDemoLeverDialog
import com.unionftech.common.R.string
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpFragment
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.ToastUtils


class DemoAccountListFragment : BaseMvpFragment(), IUpdate,
    AccountContract.IDemoTradeListView,
    AccountContract.IModifyLeverView {
    private val mTvGuideText by lazy { mRootView.findViewById<TextView>(R.id.tv_guide_text) }
    private val mTvEmptyText by lazy { mRootView.findViewById<TextView>(R.id.tv_empty_text) }
    private val mLlEmptyContainer by lazy { mRootView.findViewById<LinearLayout>(R.id.ll_empty_container) }
    private val mRvDemoAccount by lazy { mRootView.findViewById<RecyclerView>(R.id.rv_demo_account) }
    private val mAccountList = mutableListOf<TradeAccountModel>()
    private lateinit var mAdapter: AccountInfoListAdapter
    private var mCallBack: ((show: Boolean) -> Unit)? = null

    @InjectPresenter
    private lateinit var mAccountPresenter: AccountPresenter

    private val mLeverList = listOf(1, 50, 100, 200, 300, 400, 500)

    companion object {
        private const val TAG = "DemoAccountListFragment"
        private const val MAX_ACCOUNT_COUNT = 5

        @JvmStatic
        fun newInstance() = DemoAccountListFragment().apply {
            arguments = Bundle().apply {

            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {}
    }


    override fun inflaterContentView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_demo_account_list, container, false)
    }

    override fun initData() {
        super.initData()
        mAdapter = AccountInfoListAdapter(mAccountList)
    }

    fun setCallBack(callBack: (show: Boolean) -> Unit) {
        mCallBack = callBack
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvEmptyText.text = DynamicResourceManager.getString(string.without_demo_account)
        mTvGuideText.text = DynamicResourceManager.getString(string.goto_create_demo_account)
    }

    override fun setListener() {
        super.setListener()
        GlobalInfoManager.getInstance().addListener(this)
        mTvGuideText.setOnClickListener(this)
        mAdapter.setChildItemClickListener { view, position ->
            when (view.id) {
                R.id.tv_lever_in_card, R.id.iv_modify_lever_in_card -> {
                    //修改杠杆
                    mAccountList.getOrNull(position)?.also {
                        //若该账号资产为0，修改杠杆按钮置灰不可点击；
                        if (it.assets > 0.0) {
                            showModifyLeverDialog(it.leverage, it.tradeNo)
                        }
                    }
                }
            }
        }
    }

    private fun showModifyLeverDialog(leverage: Int, tradeNo: String) {
        val list = mutableListOf<String>()
        var leverIndex = -1
        mLeverList.forEachIndexed { index, lever ->
            list.add("1:${lever}")
            if (lever == leverage) {
                leverIndex = index
            }
        }
        val dialog = ModifyDemoLeverDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.modify_trade_lever))
            .setCurrentIndex(leverIndex)
            .setItemData("1:${leverage}", list)
            .setCallBack { selectIndex ->
                mLeverList.getOrNull(selectIndex)?.also { result ->
                    requestModifyLever(result, tradeNo)
                }
            }.show()
    }

    private fun requestModifyLever(leverage: Int, tradeNo: String) {
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mAccountPresenter.modifyDemoLeverage(userToken, ModifyDemoLeverRequest(leverage, tradeNo))
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        setupRecyclerView()
        loadData()
    }

    private fun setupRecyclerView() {
        mRvDemoAccount.layoutManager =
            LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
        mRvDemoAccount.adapter = mAdapter
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.tv_guide_text -> {
                AddDemoTradeAccountActivity.startThis(mContext)
            }
        }
    }

    override fun loadData() {
        super.loadData()
        mAccountList.clear()
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mAccountPresenter.getUserDemoAccountList(userToken)
    }

    override fun handleModifyLever(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            ToastUtils.longToast(DynamicResourceManager.getString(string.modify_lever_successful))
            loadData()
        } else {
            LogUtils.d(TAG, "handleModifyLever error->$response")
            response.toast()
        }
    }

    override fun handleUserDemoAccountList(result: ResponseResult<DemoAccountInfo>) {
        if (result.code == ResponseResult.SUCCESS_CODE) {
            result.data?.also { info ->
                updateAccountList(info)
            }
        } else {
            result.toast()
            LogUtils.d(TAG, "handleUserDemoAccountList error->$result")
        }
    }

    private fun updateAccountList(info: DemoAccountInfo) {
        val list = mutableListOf<DemoTradeAccount>()
        list.addAll(info.enable)
        list.addAll(info.disable)
        if (list.isEmpty()) {
            mRvDemoAccount.visibility = View.GONE
            mLlEmptyContainer.visibility = View.VISIBLE
            mTvEmptyText.text = DynamicResourceManager.getString(string.without_demo_account)
            mTvGuideText.visibility = View.VISIBLE
            mTvGuideText.text = DynamicResourceManager.getString(string.goto_create_demo_account)
        } else {
            mRvDemoAccount.visibility = View.VISIBLE
            mLlEmptyContainer.visibility = View.GONE
        }
        for (account in list) {
            val accountModel = account.change2TradeAccountModel()
            mAccountList.add(accountModel)
        }
        //检查虚拟账号是否到达上限
        val hide = mAccountList.size == MAX_ACCOUNT_COUNT
        mCallBack?.invoke(!hide)
        mAdapter.notifyDataSetChanged()
    }

    override fun onUpdate(obj: Any?) {
        if (obj is Int) {
            if (obj == GlobalInfoManager.UPDATE_DEMO_LIST) {
                loadData()
            }
        }
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }


}